package com.edu.whty.service.impl;

import com.edu.whty.common.tools.GUIDGenerator;
import com.edu.whty.dao.TbUserTextbookChapterDao;
import com.edu.whty.dao.TbUserTextbookCmsDirDao;
import com.edu.whty.dao.UserTextbookDao;
import com.edu.whty.entity.cloud.Chapter;
import com.edu.whty.entity.usertextbook.TbUserTextbookChapter;
import com.edu.whty.entity.usertextbook.TbUserTextbookCmsDir;
import com.edu.whty.entity.usertextbook.UserTextBook;
import com.edu.whty.service.UserTextBookService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserTextBookServiceImpl implements UserTextBookService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserTextbookDao userTextbookDao;

    @Autowired
    private TbUserTextbookChapterDao userTextbookChapterDao;

    @Autowired
    private TbUserTextbookCmsDirDao tbUserTextbookCmsDirMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value("${rrtbk.isCloud}")
    private boolean isCloud;

    @Override
    public List<UserTextBook> listUserTextBookByUserId(UserTextBook userTextBook) throws Exception {
        return userTextbookDao.listUserTextBookByUserId(userTextBook);
    }

    @Override
    public boolean isAdd(UserTextBook userTextBook) throws Exception {
        int count = userTextbookDao.checkTextBook(userTextBook);
        return count > 0 ? true : false;
    }

    @Override
    public UserTextBook saveTextBook(UserTextBook userTextBook) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("saveTextBook:" + userTextBook);
        }

        userTextBook.setId(GUIDGenerator.getGUID());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userTextBook.setCreateTime(sdf.format(new Date()));
        userTextBook.setStatus("0");
        //校园主机保存教材时数据标识为未同步
        userTextBook.setIsSync(isCloud ? "0" : "1");

        userTextbookDao.save(userTextBook);

        return userTextBook;
    }

    /**
     * 根据ID获取UserTextBook
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public UserTextBook loadUserTextBook(String id) throws Exception {
        return userTextbookDao.getById(id);
    }

    @Override
    public void delteTextBookById(String id) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id", id);
        paramMap.put("delTime", new Date());

        userTextbookDao.deleteLogicById(paramMap);
    }

    /**
     * 添加自定义教材
     *
     * @param userId
     * @param textBookId
     * @throws Exception
     */
    @Override
    public void addCmsChapter(TbUserTextbookCmsDir textBookDir) throws Exception {
        textBookDir.setId(GUIDGenerator.getGUID());
        textBookDir.setStatus("0");
        textBookDir.setCreateTime(new Date());
        tbUserTextbookCmsDirMapper.save(textBookDir);
    }

    /**
     * 查询教材章节
     *
     * @param param
     * @return
     * @throws Exception
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public List<TbUserTextbookChapter> loadUserTextBookChapter(Map<String, Object> param) throws Exception {
        List<TbUserTextbookChapter> chapterList = null;
        List<TbUserTextbookChapter> chapterListAll = userTextbookChapterDao.loadUserTextBookChapter(param);
        //去重过滤
        List<String> list = new ArrayList<String>();
        Map chapterMap = new HashMap();
        for (TbUserTextbookChapter chapter : chapterListAll) {
            if (null == chapterMap.get(chapter.getChapterId())) {
                if (null == chapterList) {
                    chapterList = new ArrayList<TbUserTextbookChapter>();
                }
                chapterList.add(chapter);
                chapterMap.put(chapter.getChapterId(), chapter.getId());
            } else {
                //该章节第2次出现
                list.add(chapter.getId());
            }
        }
        //逻辑删除重复的章节
        if (list.size() > 0) {
            userTextbookChapterDao.deleteByIdList(list);
        }
        return chapterList;
    }

    @Override
    public void saveTextBookBatch(List<UserTextBook> list) throws Exception {
        userTextbookDao.saveTextBookBatch(list);
    }

    @Override
    public void saveTextBookChapterBatch(List<TbUserTextbookChapter> list) throws Exception {
        userTextbookDao.saveTextBookChapterBatch(list);
    }

    @Override
    public void syncUserTextBookBatch(List<Map<String, Object>> list, String type) {
        if ("INSERT".equals(type)) {
            userTextbookDao.syncSaveUserTextBookBatch(list);
        } else if ("UPDATE".equals(type)) {
            userTextbookDao.syncUpdateUserTextBookBatch(list);
        } else if ("DELETE".equals(type)) {
            userTextbookDao.syncDeleteUserTextBookBatch(list);
        }
    }

    @Override
    public void syncSaveOrUpdateBatch(List<Map<String, Object>> list) {
        userTextbookDao.syncSaveOrUpdateBatch(list);
    }

    @Override
    public void syncUserTextBookChapterBatch(List<Map<String, Object>> list, String type) {
        if ("INSERT".equals(type)) {
            userTextbookChapterDao.syncSaveUserTextBookChapterBatch(list);
        } else if ("UPDATE".equals(type)) {
            userTextbookChapterDao.syncUpdateUserTextBookChapterBatch(list);
        } else if ("DELETE".equals(type)) {
            userTextbookChapterDao.syncDeleteUserTextBookChapterBatch(list);
        }
    }

    @Override
    public List<Map<String, Object>> getUpSyncUserTextBook() throws Exception {
        return userTextbookDao.getUpSyncUserTextBook();
    }

    @Override
    public void finishUpSyncUserTextBook() throws Exception {
        userTextbookDao.finishUpSyncUserTextBook();
    }

    @Override
    public void compareSyncUserTextBook(List<String> userIdList, List<UserTextBook> list) throws Exception {
        List<String> compareIdList = userTextbookDao.getIdListByUserId(userIdList);
        List<UserTextBook> insertList = new ArrayList<UserTextBook>();
        List<UserTextBook> updateList = new ArrayList<UserTextBook>();
        for (UserTextBook userTextBook : list) {
            if (compareIdList.contains(userTextBook.getId())) {
                updateList.add(userTextBook);
            } else {
                insertList.add(userTextBook);
            }
        }

        if (insertList.size() > 0) {
            userTextbookDao.saveTextBookBatch(insertList);
        }
        if (updateList.size() > 0) {
            userTextbookDao.updateTextBookBatch(updateList);
        }
    }



    /**
     * 根据条件查询子树
     * @return
     * @throws Exception
     */
    @Override
    public List<Chapter> selectSubTreeList(Chapter model) throws Exception {
        List<Chapter> list = new ArrayList<Chapter>();
        if (StringUtils.isNotBlank(model.getTextbookId()) && StringUtils.isBlank(model.getChapterPid())) {
            String sql="select * from t_chapter where textbook_id=? and status='0' order by sort_num";
            list=jdbcTemplate.query(sql, new Object[]{model.getTextbookId()}, new BeanPropertyRowMapper<Chapter>(Chapter.class));
        }

        if (StringUtils.isNotBlank(model.getChapterPid())) {
            String chaperSql="select * from t_chapter where chapter_pid=? and status='0'";
            if (StringUtils.isNotBlank(model.getTextbookId())) {
                chaperSql=chaperSql+" and textbook_id='"+model.getTextbookId().trim()+"'";
            }
            getChaper(model.getChapterPid(), list, chaperSql+" order by sort_num");
        }

        if (StringUtils.isNotBlank(model.getChapterId())) {
            String chapterSql = "select * from t_chapter where chapter_id=? and status='0'";

            List<Chapter> chapterList=jdbcTemplate.query(chapterSql, new Object[]{model.getChapterId()},new BeanPropertyRowMapper<Chapter>(Chapter.class));
            Chapter chapter=chapterList.get(0);
            list.add(chapter);
            String chaperSql="select * from t_chapter where chapter_pid=? and status='0' order by sort_num";
            getChaper(model.getChapterPid(), list, chaperSql);
        }
        return list;
        //return getSqlSession().selectList("ChapterMapper.selectSubTreeList", model);
    }

    /**
     * 根据父章节Id 查询所有子章节Id
     *
     * @param chapterId
     * @param result
     */
    public  void getChaper(String chapterId,List<Chapter> result,String chaperSql){
        //String chaperSql="select * from t_chapter where chapter_pid=? and status ='0' order by sort_num ";
        List<Chapter> list=jdbcTemplate.query(chaperSql, new Object[]{chapterId},new BeanPropertyRowMapper<Chapter>(Chapter.class));
        for (Chapter chapter : list) {
            result.add(chapter);
            getChaper(chapter.getChapterId(), result,chaperSql);
        }
    }



}
